layui.use(['form','tree','element','laydate','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;
    var laydate = layui.laydate;

    laydate.render({
        elem: '#downAcquisitionTime'
    });
    laydate.render({
        elem: '#upAcquisitionTime'
    });
    //采集设备数据
    $.get("/equipment/list",function (data) {
        /*$("#equipment-list").append('<option value="">请选择</option>');*/
        $.each(data.data,function (i,ele) {
            $("#equipment-list").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
        });
        form.render('select');
        //刷新设备对应的数据采集项
        form.on('select(equipment-list)',function (data) {
            $.get("/equipment/channel/query?equipmentId=" + data.value,function (data) {
                $("#checkItem").html("");
                $("#checkItem").append('<option value="">请选择</option>');
                $.each(data.data,function (i,ele) {
                    $("#checkItem").append('<option value="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</option>');
                });
                form.render('select');
            });
        });
    });
    //检测项目数据
    $.get("/checkitem/list",function (data) {
        $.each(data.data,function (i,ele) {
            $("#checkItem").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
        });
        form.render('select');
    });

    //列表数据
    window.myindex = layer.load(2);
    var option = {
        elem: '#tableList',
        url : '/search/datarecord/page',
        cellMinWidth : 95,
        page : true,
        height : "full-150",
        limits : [10,15,20,25],
        limit : 15,
        id : "listTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'equipmentName', title: '所属设备', minWidth:100, align:"center"},
            {field: 'channelNo', title: '通道号', minWidth:200, align:'center'},
            {field: 'checkItemName', title: '采集项', minWidth:100, align:"center"},
            {field: 'processedData', title: '数据',  align:'center'},
            {field: 'unit', title: '单位',  align:'center'},
            {field: 'acquisitionTime', title: '采集时间', align:'center',minWidth:150,sort:true, templet:function(d){
                    //处理时间
                    var date = new Date(d.acquisitionTime);
                    /*console.log(d.acquisitionTime);*/
                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+ " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                }
            },
            {field: 'reportingTime', title: '上报时间', align:'center',minWidth:150,sort:true, templet:function(d){
                    //处理时间
                    var date = new Date(d.reportingTime);
                    /*console.log(d.acquisitionTime);*/
                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+ " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                }
            },
            {title: '操作', minWidth:175, templet:'#tableListBar',fixed:"right",align:"center"}
        ]],
        done: function (res, curr, count) {
            layer.close(myindex);
        }
    };

    //场景数据
    var height = $(document).height();
    $(".orgbox").css('height',(height - 40) + "px");
    $(window).on("resize",function () {
        $(".orgbox").css('height',(height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            //刷新右侧设备列表和检测项目列表
            $.get("/equipment/query?sceneId=" + item.id,function (data) {
                $("#equipment-list").html('');
                $("#equipment-list").append('<option value="">请选择</option>');
                $.each(data.data,function (i,ele) {
                    $("#equipment-list").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
                });
                form.render('select');
            });

            option.url = '/search/datarecord/page/query';
            option.where = {sceneId: item.id};
            myindex = layer.load(2);
            table.render(option);
        },
        nodes:null
    };
    //异步加载设备所处场景数据
    $.get('/scene/tree',function(data) {
        if (data.data.length != 0) {
            data.data[0].spread = true;
        }
        treeData.nodes = data.data;
        layui.tree(treeData);
    });

    //设备列表
    var tableIns = table.render(option);

    //搜索设备信息
    $(".search_btn").on("click",function(){
        var equipmentId = $("#equipment-list").val();
        var checkItemId = $("#checkItem").val();
        var upAcquisitionTime = $("#upAcquisitionTime").val();
        var downAcquisitionTime = $("#downAcquisitionTime").val();
        var searchObj = {};
        if(equipmentId == ''){
            layer.msg("请选择搜索设备");
            return;
        }
        searchObj.equipmentId = equipmentId;
        searchObj.checkItemId = checkItemId;
        if (upAcquisitionTime != null && upAcquisitionTime != "") {
            searchObj.upAcquisitionTime = upAcquisitionTime + "T00:00:00Z";
        }
        if (downAcquisitionTime != null && downAcquisitionTime != "") {
            searchObj.downAcquisitionTime = downAcquisitionTime + "T00:00:00Z";
        }
        option.url = '/search/datarecord/page/query';
        option.method = 'post';
        option.where = searchObj;
        myindex = layer.load(2);
        table.render(option);
        //测试
        /*searchObj.page = 0;
        searchObj.limit = 1000;
        $.get('/datarecord/forecast/arima',searchObj,function (data) {
            console.log(data);
        });*/

    });

    //手动更新索引库
    $(".update_btn").click(function () {
        //列表数据
        window.myindex = layer.load(2);
        $.get("/search/datarecord/import",function (data) {
            layer.close(myindex);
            layer.msg("导入成功！");
        });
    });

    //列表操作
    table.on('tool(tableList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            var index = layui.layer.open({
                title : "查看记录详细信息",
                type : 2,
                content : "datarecordView?id=" + data.id,
                area: ['100%',$(document).height() - 30 + 'px'],
                success : function(){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回设备列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此设备？',{icon:3, title:'提示信息'},function(index){
                $.get("/datarecord/delete?id=" + data.id,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });

});